<template>
  <div class="root">
    <div class="divBox">
      <div class="content-container">
        <div class="cardBody" v-loading="loading">
          <span class="header">碳信用详情</span
          ><span class="asset-title">{{ assetDetail.projectName || '--' }}</span>
          <el-divider></el-divider>
          
          <!-- 基本信息 -->
          <img src="@/assets/icon/icon_plant.png" alt="" class="icon" />
          <span class="asset-little-title">基本信息</span>
          <div class="basic-divx">
            <div class="item-div">
              <span class="item-title">核证标准</span> <br /><span
                class="item-content"
                >{{ assetDetail.certificationCriteria || '--' }}</span
              >
            </div>
            <div class="item-div">
              <span class="item-title">采用方法学</span> <br /><span
                class="item-content"
                >{{ assetDetail.carbonMethodologyName || '--' }}</span
              >
            </div>
            <div class="item-div">
              <span class="item-title">类型</span> <br /><span
                class="item-content"
                >{{ assetDetail.industryCodeName || '--' }}</span
              >
            </div>
            <div class="item-div">
              <span class="item-title">核证机构</span> <br /><span
                class="item-content"
                >{{ assetDetail.certifiedAgencyName || '--' }}</span
              >
            </div>
            <div class="item-div">
              <span class="item-title">有效期</span> <br /><span
                class="item-content"
                >{{ assetDetail.expiryDate || '--' }}</span
              >
            </div>
            <div class="item-div">
              <span class="item-title">签发日期</span> <br /><span
                class="item-content"
                >{{ assetDetail.issuingDate || '--' }}</span
              >
            </div>
            <div class="item-div">
              <span class="item-title">签发机构</span> <br /><span
                class="item-content"
                >{{ assetDetail.issuingAgency || '--' }}</span
              >
            </div>
            <div class="item-div">
              <span class="item-title">签发凭证</span>
              <br /><span
                class="item-content"
                :style="styles(assetDetail.issuingCertificatesFileName)"
                @click="toIssueFile"
                >{{ (assetDetail.issuingCertificatesFileName || '') | file }}</span
              >
            </div>
            <div class="item-div">
              <span class="item-title">一级市场持有机构</span> <br /><span
                class="item-content"
                >{{ assetDetail.tenantName || '--' }}</span
              >
            </div>
          </div>
          
          <!-- 项目信息 -->
          <br />
          <br />
          <img src="@/assets/icon/icon_plant.png" alt="" class="icon" />
          <span class="asset-little-title">项目信息</span
          ><span v-if="assetDetail.projectIntroduction && assetDetail.projectIntroduction != '--'" class="detail" @click="toDetail"
            >查看详情<i class="el-icon-d-arrow-right"></i
          ></span>
          <div class="basic-div" style="padding: 20px 16px 20px 16px">
            <p class="paragraph">
              {{ assetDetail.projectIntroduction || '暂无项目介绍' }}
            </p>
          </div>
          
          <!-- 持仓信息 -->
          <br />
          <br />
          <img src="@/assets/icon/icon_plant.png" alt="" class="icon" />
          <span class="asset-little-title">持仓信息</span
          ><span class="detail" @click="toDetail"
            >查看详情<i class="el-icon-d-arrow-right"></i
          ></span>
          <div class="basic-div" style="height: 89px">
            <div class="item-div">
              <span class="item-title">资产状态</span> <br /><span
                class="item-content"
                >{{ assetDetail.assetsStatusName || '--' }}</span
              >
            </div>
            <div class="item-div">
              <span class="item-title">持仓总量(tCO2e)</span> <br /><span
                class="item-content"
                >{{ setNumber(assetDetail.total)}}</span
              >
            </div>
            <div class="item-div">
              <span class="item-title">资产估值(¥)</span> <br /><span
                class="item-content"
                >{{ setNumber(assetDetail.valuation) }}</span
              >
            </div>
            <div class="item-div">
              <span class="item-title">可用数量(tCO2e)</span> <br /><span
                class="item-content"
                >{{ setNumber(assetDetail.availableAmount) }}</span
              >
            </div>
            <div class="item-div">
              <span class="item-title">锁定数量(tCO2e)</span> <br /><span
                class="item-content"
                >{{ setNumber(assetDetail.lockedAmount) }}</span
              >
            </div>
            <div class="item-div">
              <span class="item-title">冻结数量(tCO2e)</span> <br /><span
                class="item-content"
                >{{ setNumber(assetDetail.frozenAmount) }}</span
              >
            </div>
          </div>
          
          <!-- 交易信息 -->
          <br />
          <br />
          <img src="@/assets/icon/icon_plant.png" alt="" class="icon" />
          <span class="asset-little-title">交易信息</span
          ><span class="detail" @click="toCarbonExchangeWebsite"
            >查看详情<i class="el-icon-d-arrow-right"></i
          ></span>
          <div class="basic-div" style="height: 89px">
            <div class="item-div">
              <span class="item-title">交易状态</span> <br /><span
                class="item-content"
                >{{ assetDetail.transactionStatusName || '--' }}</span
              >
            </div>
            <div class="item-div">
              <span class="item-title">交割场所</span> <br /><span
                class="item-content"
                >{{ assetDetail.carbonExchangeName || '--' }}</span
              >
            </div>
            <div class="item-div">
              <span class="item-title">购入凭证</span>
              <br /><span
                class="item-content"
                style="cursor: pointer; color: #126fff"
                @click="toBuyFile"
                >{{ (assetDetail.buyCertificateFileName || '') | file }}</span
              >
            </div>
            <div class="item-div">
              <span class="item-title">购入单价(¥)</span> <br /><span
                class="item-content"
                >{{ assetDetail.buyUnitPrice || '--' }}</span
              >
            </div>
            <div class="item-div">
              <span class="item-title">购入总价(¥)</span> <br /><span
                class="item-content"
                >{{ assetDetail.buyTotalPrice || '--' }}</span
              >
            </div>
            <div class="item-div">
              <span class="item-title">购入日期</span> <br /><span
                class="item-content"
                >{{ assetDetail.buyDate || '--' }}</span
              >
            </div>
          </div>
          
          <!-- 操作按钮 -->
          <br />
          <br />
          <div class="basic-div" style="height: 89px; background-color: white">
            <button
              style="width: 96px; float: right"
              class="light-green-btn"
              @click="insideTransaction"
            >
              场内交易
            </button>
            <button
              style="width: 96px; float: right; margin-right: 20px"
              class="light-green-btn"
              @click="ousideTransaction"
            >
              场外上架
            </button>
            <button
              style="width: 96px; float: right; margin-right: 20px"
              class="normal-white-btn"
              @click="goback"
            >
              返回
            </button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { carbonAssetDetail, addcarbonAssetMarket, changeCredit } from "@/api/carbonAssetApi";

export default {
  name: "assetDetail",
  data() {
    return {
      assetId: 0,
      assetDetail: {},
      loading: true,
      dialogFormVisible: false,
      exchangeList: [],
      tradeMethods: [],
      showQuotation: false,
      form: {
        id: 0,
        tradeQuantity: "",
        negotiatedPrice: "",
        expirationDate: "",
        deliveryTime: "",
        deliveryMethod: "",
        deliveryExchange: "",
        projectType: "",
        projectId: null,
        direction: "0280000002",
        status: "",
        assetType: "0140000001",
        institutionName: "",
      },
      title: "",
    };
  },
  mounted() {
    this.loadDetail();
    this.exchangeList = [
      { name: '全国碳排放权交易中心', value: '0170000001' },
      { name: '北京环境交易所', value: '0170000002' },
      { name: '上海环境能源交易所', value: '0170000003' }
    ];
    this.tradeMethods = [
      { name: '协议转入', value: '0190000001' },
      { name: '竞价交易', value: '0190000002' },
      { name: '定价交易', value: '0190000003' }
    ];
  },
  filters: {
    file(value) {
      if (value) {
        let values = value.split("/");
        return values[values.length - 1];
      }
    },
  },
  methods: {
    setNumber(str) {
      return str ? str.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ',') : '--';
    },
    
    styles(str) {
      if (str) {
        return "cursor: pointer; color: #126fff";
      } else {
        return "cursor: default; color: #126fff";
      }
    },
    
    toDetail() {
      this.$router.push("/account/wallet");
    },
    
    toCarbonExchangeWebsite() {
      if (this.assetDetail.carbonExchangeWebsite) {
        window.open(this.assetDetail.carbonExchangeWebsite);
      }
    },
    
    toBuyFile() {
      if (this.assetDetail.buyCertificate) {
        window.open(this.assetDetail.buyCertificate);
      }
    },
    
    toIssueFile() {
      if (this.assetDetail.issuingCertificates) {
        window.open(this.assetDetail.issuingCertificates);
      }
    },
    
    loadDetail() {
      let id = this.$route.query;
      this.assetId = id.id;
      this.loading = true;
      
      if (!this.assetId) {
        this.$message.error('缺少资产ID参数');
        this.loading = false;
        return;
      }
      
      carbonAssetDetail(this.assetId).then(
        (res) => {
          this.loading = false;
          if (res && res.data) {
            this.assetDetail = res.data;
            this.assetDetail.issuingDate = this.assetDetail.issuingDate
              ? this.formatDate(this.assetDetail.issuingDate)
              : "--";
            this.assetDetail.expiryDate = this.assetDetail.expiryDate
              ? this.formatDate(this.assetDetail.expiryDate)
              : "--";
            this.assetDetail.buyDate = this.assetDetail.buyDate
              ? this.formatDate(this.assetDetail.buyDate)
              : "--";
            for (var i in this.assetDetail) {
              this.assetDetail[i] = this.assetDetail[i]
                ? this.assetDetail[i]
                : "--";
              if (this.assetDetail[i] == " ") {
                this.assetDetail[i] = "--";
              }
            }
          } else {
            this.$message.warning('未获取到资产详情数据');
            this.loadMockDetail();
          }
        },
        (err) => {
          this.loading = false;
          console.error('获取碳信用详情失败:', err);
          this.$message.error('获取资产详情失败，将显示模拟数据');
          // 使用模拟数据
          this.loadMockDetail();
        }
      );
    },
    
    loadMockDetail() {
      this.assetDetail = {
        id: this.assetId,
        projectName: '太阳能发电项目',
        certificationCriteria: 'VCS',
        carbonMethodologyName: 'CM-001-V01',
        industryCodeName: '能源工业',
        certifiedAgencyName: '核证机构A',
        expiryDate: '2025-01-15',
        issuingDate: '2024-01-15',
        issuingAgency: '签发机构A',
        issuingCertificatesFileName: 'certificate.pdf',
        issuingCertificates: 'http://example.com/certificate.pdf',
        tenantName: '碳达峰科技有限公司',
        projectIntroduction: '这是一个太阳能发电项目，通过光伏发电减少碳排放，项目规模为10MW，预计年发电量1200万度，年减排量约6000吨CO2e。',
        assetsStatusName: '正常',
        total: 1000,
        valuation: 50000,
        availableAmount: 800,
        lockedAmount: 150,
        frozenAmount: 50,
        transactionStatusName: '可交易',
        carbonExchangeName: '全国碳排放权交易中心',
        buyCertificateFileName: 'purchase.pdf',
        buyCertificate: 'http://example.com/purchase.pdf',
        buyUnitPrice: 50,
        buyTotalPrice: 50000,
        buyDate: '2024-01-20',
        carbonExchangeWebsite: 'https://www.cneeex.com'
      };
    },
    
    formatDate(date) {
      let datelist = date.split(" ");
      return datelist[0];
    },
    
    ousideTransaction() {
      this.dialogFormVisible = true;
      this.form.id = this.assetDetail.id;
      this.form.projectId = this.assetDetail.carbonProjectId;
      this.form.projectType = this.assetDetail.fieldChildCode;
      this.form.assetType = this.assetDetail.transactionStatus;
      this.form.institutionName = this.assetDetail.projectName;
      this.title = this.assetDetail.projectName;
      this.form.deliveryMethod = "0190000000";
      this.form.deliveryExchange = "0170000000";
    },
    
    goback() {
      this.$router.go(-1);
    },
    
    insideTransaction() {
      this.$router.push("/trade/account/exchange");
    },
    
    submit() {
      const data = {
        id: this.form.id,
        transactionStatus: "0160000001",
      };
      if (this.assetDetail.availableAmount && this.assetDetail.availableAmount < this.form.tradeQuantity) {
        this.$message.warning("出售数量不能大于可用量");
        return;
      }
      addcarbonAssetMarket(this.form).then(
        (res) => {
          changeCredit(data).then(
            (res) => {
              this.$message.success("操作成功");
              this.dialogFormVisible = false;
              this.showQuotation = true;
              this.loadDetail();
            },
            (err) => {}
          );
        },
        (err) => {
          this.$message.error("操作失败");
        }
      );
    },
  },
};
</script>

<style lang="scss" scoped>
.root {
  background: #f2f5f7;
}

.divBox {
  margin: 20px;
  background: #ffffff;
  box-shadow: 0px 2px 8px 0px #eaf0f3;
  border-radius: 8px;
}

.content-container {
  display: flex;
  flex-direction: column;
  width: 100%;
}

.cardBody {
  margin: 30px 30px 30px 30px;
}

.header {
  width: 95px;
  height: 18px;
  font-weight: 500;
  color: #24a776;
}

.asset-title {
  width: 396px;
  height: 18px;
  font-weight: 500;
  color: #242b35;
  margin-left: 20px;
}

.el-divider {
  margin-top: 30px;
}

.icon {
  height: 16px;
  width: 22px;
}

.asset-little-title {
  width: 64px;
  height: 16px;
  font-weight: 500;
  color: #424c5c;
  margin-left: 10px;
}

@media screen and (min-width: 1360px) {
  .basic-divx {
    width: 95%;
    min-height: 200px;
    background: #f7f9fc;
    border-radius: 6px;
    margin-left: 30px;
    margin-top: 30px;
  }
}

@media screen and (max-width: 1360px) {
  .basic-divx {
    width: 95%;
    min-height: 300px;
    background: #f7f9fc;
    border-radius: 6px;
    margin-left: 30px;
    margin-top: 30px;
  }
}

.basic-div {
  width: 95%;
  min-height: 200px;
  background: #f7f9fc;
  border-radius: 6px;
  margin-left: 30px;
  margin-top: 30px;
}

.item-title {
  width: 56px;
  height: 14px;
  font-weight: 400;
  color: #5e6c84;
}

.item-content {
  width: 42px;
  height: 15px;
  font-weight: 400;
  color: #424c5c;
  position: relative;
  top: 15px;
}

.item-div {
  float: left;
  margin: 24px 20px 20px 16px;
  width: 150px;
  height: 40px;
}

.paragraph {
  width: 95%;
  height: 108px;
  font-weight: 400;
  color: #808ea5;
  text-align: justify;
}

.detail {
  width: 56px;
  height: 14px;
  font-weight: 400;
  color: #24a776;
  margin-left: 15px;
  cursor: pointer;
}

.light-green-btn {
  background: #24a776;
  color: white;
  border: none;
  padding: 8px 16px;
  border-radius: 4px;
  cursor: pointer;
}

.normal-white-btn {
  background: white;
  color: #333;
  border: 1px solid #ddd;
  padding: 8px 16px;
  border-radius: 4px;
  cursor: pointer;
}
</style>